package com.leyou.auth.service.impl;

import com.leyou.auth.constants.RedisConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.common.constants.JwtConstants;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import feign.FeignException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class UserAuthServiceImpl implements UserAuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void userLogin(String username, String password, HttpServletResponse response) {

        UserDTO userDTO = null;

        try {
            userDTO = userClient.quereyByUserNameAndPassword(username, password);
            if (userDTO == null){
                throw new LyException(400, "用户名或密码错误");
            }

        } catch (FeignException e) {

            throw new LyException(e.status(), e.contentUTF8());
        }

        UserDetail userDetail = UserDetail.of(userDTO.getId(), userDTO.getUsername());
        String jwt = jwtUtils.createJwt(userDetail);
        writeCookie(response, jwt);


    }

    @Override
    public void userLogout(HttpServletRequest request, HttpServletResponse response) {
        String jwt = CookieUtils.getCookieValue(request, JwtConstants.COOKIE_NAME);
        Payload payload = null;
        try {
            payload = jwtUtils.parseJwt(jwt);
        } catch (Exception e) {
            return;
        }

        CookieUtils.deleteCookie(JwtConstants.COOKIE_NAME, JwtConstants.DOMAIN, response);

        UserDetail userDetail = payload.getUserDetail();

        redisTemplate.delete(RedisConstants.JTI_KEY_PREFIX + userDetail.getId());
    }

    public void writeCookie(HttpServletResponse response, String token){
        Cookie cookie = new Cookie(JwtConstants.COOKIE_NAME, token);
        //cookie的作用域
        //cookie.setDomain(JwtConstants.DOMAIN);

        //是否禁止操作cookie, 避免xss攻击
        cookie.setHttpOnly(true);

        //cookie的有效期
        cookie.setMaxAge(-1);

        //cookie的作用路径
        cookie.setPath("/");

        response.addCookie(cookie);
    }
}
